package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.controller.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("FoodRestController")
public class FoodRestController extends CmiEmaController {

	/**
	 * Create a new Food entity
	 * 
	 */
	@RequestMapping(value = "/newFood", method = RequestMethod.POST)
	@ResponseBody
	public Object newFood(@RequestBody Food food) {
		foodService.saveFood(food);
		return JSONObject.parse(cmiPsonService.toJsonString(foodDAO.findFoodByPrimaryKey(food.getId()), 2));
	}

	@RequestMapping(value = "/restNewFood", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewFood(@RequestBody String foodJson) {
		Food food = new Gson().fromJson(foodJson, Food.class);
		appendReferences(food);
		foodService.saveFood(food);
		return JSONObject.parse(cmiPsonService.toJsonString(foodDAO.findFoodByPrimaryKey(food.getId()), 2));
	}

	@RequestMapping(value = "/saveFood", method = RequestMethod.PUT)
	@ResponseBody
	public Food saveFood(@RequestBody Food food) {
		foodService.saveFood(food);
		return foodDAO.findFoodByPrimaryKey(food.getId());
	}

	@RequestMapping(value = "/restSaveFood", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveFood(@RequestBody String foodJson) {
		Food food = new Gson().fromJson(foodJson, Food.class);
		appendReferences(food);
		CmiPsonService cmiPsonService = new CmiPsonService();
		foodService.saveFood(food);
		return JSONObject.parse(cmiPsonService.toJsonString(foodDAO.findFoodByPrimaryKey(food.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteFood/{foodId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteFood(@PathVariable Integer foodId) {
		Food food = foodDAO.findFoodByPrimaryKey(foodId);
		foodService.deleteFood(food);
	}

	@RequestMapping(value = "/restConfirmDeleteFoods")
	@ResponseBody
	public Object restConfirmDeleteFoods(@RequestBody Set<Integer> deleteFoodsIds) {
		Set<Food> deleteFoods = foodDAO.findFoodsByIds(deleteFoodsIds);
		Set<Food> referencedFoods = foodService.loadReferenceFoods(deleteFoods);
		deleteFoods.removeAll(referencedFoods);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedFoods);
		jsonObject.put("deleteEntitys", deleteFoods);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteFoods")
	@ResponseBody
	public Object restDeleteFoods(@RequestBody Set<Food> deleteFoods) {
		Iterator<Food> iterator = deleteFoods.iterator();
		while (iterator.hasNext()) {
			Food currentFood = iterator.next();
			foodService.deleteFood(currentFood);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listFoods");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadFood/{foodId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFood(@PathVariable Integer foodId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(foodDAO.findFoodByPrimaryKey(foodId), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFoodBrand/{foodId}/brand", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodBrand(@PathVariable Integer foodId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(foodDAO.findFoodByPrimaryKey(foodId).getBrand(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFoodExpire/{foodId}/expire", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodExpire(@PathVariable Integer foodId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(foodDAO.findFoodByPrimaryKey(foodId).getExpire(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFoodStoremethod/{foodId}/storemethod", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodStoremethod(@PathVariable Integer foodId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(foodDAO.findFoodByPrimaryKey(foodId).getStoremethod(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFoodProducer/{foodId}/producer", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodProducer(@PathVariable Integer foodId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(foodDAO.findFoodByPrimaryKey(foodId).getProducer(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFoodFoodtype/{foodId}/foodtype", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodFoodtype(@PathVariable Integer foodId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(foodDAO.findFoodByPrimaryKey(foodId).getFoodtype(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFoodProductcode/{foodId}/productcode", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodProductcode(@PathVariable Integer foodId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(foodDAO.findFoodByPrimaryKey(foodId).getProductcode(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFoodTaste/{foodId}/taste", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodTaste(@PathVariable Integer foodId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(foodDAO.findFoodByPrimaryKey(foodId).getTaste(), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadFoodDetectstandards/{foodId}/detectstandards/{relateddetectstandardId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodDetectstandards(@PathVariable Integer foodId,
			@PathVariable Integer relateddetectstandardId, @RequestBody CmiPagination cmiPagination) {
		Detectstandard detectstandard = detectstandardDAO.findDetectstandardByPrimaryKey(relateddetectstandardId, -1,
				-1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(detectstandard, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFoodPackingmethods/{foodId}/packingmethods/{relatedpackingmethodId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodPackingmethods(@PathVariable Integer foodId, @PathVariable Integer relatedpackingmethodId,
			@RequestBody CmiPagination cmiPagination) {
		Packingmethod packingmethod = packingmethodDAO.findPackingmethodByPrimaryKey(relatedpackingmethodId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(packingmethod, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFoodProcessmethods/{foodId}/processmethods/{relatedprocessmethodId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodProcessmethods(@PathVariable Integer foodId, @PathVariable Integer relatedprocessmethodId,
			@RequestBody CmiPagination cmiPagination) {
		Processmethod processmethod = processmethodDAO.findProcessmethodByPrimaryKey(relatedprocessmethodId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(processmethod, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFoodFoodadditives/{foodId}/foodadditives/{relatedfoodadditiveId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodFoodadditives(@PathVariable Integer foodId, @PathVariable Integer relatedfoodadditiveId,
			@RequestBody CmiPagination cmiPagination) {
		Foodadditive foodadditive = foodadditiveDAO.findFoodadditiveByPrimaryKey(relatedfoodadditiveId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(foodadditive, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFoodFoodbatchs/{foodId}/foodbatchs/{relatedfoodbatchId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodFoodbatchs(@PathVariable Integer foodId, @PathVariable Integer relatedfoodbatchId,
			@RequestBody CmiPagination cmiPagination) {
		Foodbatch foodbatch = foodbatchDAO.findFoodbatchByPrimaryKey(relatedfoodbatchId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(foodbatch, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFoodFoodmaterials/{foodId}/foodmaterials/{relatedfoodmaterialId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodFoodmaterials(@PathVariable Integer foodId, @PathVariable Integer relatedfoodmaterialId,
			@RequestBody CmiPagination cmiPagination) {
		Foodmaterial foodmaterial = foodmaterialDAO.findFoodmaterialByPrimaryKey(relatedfoodmaterialId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(foodmaterial, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFoodFoodsaleaddresss/{foodId}/foodsaleaddresss/{relatedfoodsaleaddressId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodFoodsaleaddresss(@PathVariable Integer foodId,
			@PathVariable Integer relatedfoodsaleaddressId, @RequestBody CmiPagination cmiPagination) {
		Foodsaleaddress foodsaleaddress = foodsaleaddressDAO.findFoodsaleaddressByPrimaryKey(relatedfoodsaleaddressId,
				-1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(foodsaleaddress, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFoodPictures/{foodId}/pictures/{relatedpictureId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodPictures(@PathVariable Integer foodId, @PathVariable Integer relatedpictureId,
			@RequestBody CmiPagination cmiPagination) {
		Picture picture = pictureDAO.findPictureByPrimaryKey(relatedpictureId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(picture, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFoodVideos/{foodId}/videos/{relatedvideoId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodVideos(@PathVariable Integer foodId, @PathVariable Integer relatedvideoId,
			@RequestBody CmiPagination cmiPagination) {
		Video video = videoDAO.findVideoByPrimaryKey(relatedvideoId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(video, 2, cmiPagination));
	}

	public void appendReferences(Food food) {

		Brand brand = food.getBrand();
		if (brand != null)
			food.setBrand(brandService.findBrandByPrimaryKey(brand.getId()));

		Expire expire = food.getExpire();
		if (expire != null)
			food.setExpire(expireService.findExpireByPrimaryKey(expire.getId()));

		Storemethod storemethod = food.getStoremethod();
		if (storemethod != null)
			food.setStoremethod(storemethodService.findStoremethodByPrimaryKey(storemethod.getId()));

		Producer producer = food.getProducer();
		if (producer != null)
			food.setProducer(producerService.findProducerByPrimaryKey(producer.getId()));

		Foodtype foodtype = food.getFoodtype();
		if (foodtype != null)
			food.setFoodtype(foodtypeService.findFoodtypeByPrimaryKey(foodtype.getId()));

		Productcode productcode = food.getProductcode();
		if (productcode != null)
			food.setProductcode(productcodeService.findProductcodeByPrimaryKey(productcode.getId()));

		Taste taste = food.getTaste();
		if (taste != null)
			food.setTaste(tasteService.findTasteByPrimaryKey(taste.getId()));

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Detectstandard> detectstandardsForFood = new HashSet<>();
		for (Detectstandard detectstandard_Food : food.getDetectstandardsForFood()) {
			detectstandardsForFood
					.add(detectstandardService.findDetectstandardByPrimaryKey(detectstandard_Food.getId()));
		}
		food.setDetectstandardsForFood(detectstandardsForFood);

		// 引用表是纯联系表的情况
		Set<Packingmethod> packingmethodsForFood = new HashSet<>();
		for (Packingmethod packingmethodForFood : food.getPackingmethodsForFood()) {
			packingmethodsForFood.add(packingmethodService.findPackingmethodByPrimaryKey(packingmethodForFood.getId()));
		}
		food.setPackingmethodsForFood(packingmethodsForFood);

		// 引用表是纯联系表的情况
		Set<Processmethod> processmethodsForFood = new HashSet<>();
		for (Processmethod processmethodForFood : food.getProcessmethodsForFood()) {
			processmethodsForFood.add(processmethodService.findProcessmethodByPrimaryKey(processmethodForFood.getId()));
		}
		food.setProcessmethodsForFood(processmethodsForFood);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Foodadditive> foodadditivesForFood = new HashSet<>();
		for (Foodadditive foodadditive_Food : food.getFoodadditivesForFood()) {
			foodadditivesForFood.add(foodadditiveService.findFoodadditiveByPrimaryKey(foodadditive_Food.getId()));
		}
		food.setFoodadditivesForFood(foodadditivesForFood);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Foodbatch> foodbatchsForFood = new HashSet<>();
		for (Foodbatch foodbatch_Food : food.getFoodbatchsForFood()) {
			foodbatchsForFood.add(foodbatchService.findFoodbatchByPrimaryKey(foodbatch_Food.getId()));
		}
		food.setFoodbatchsForFood(foodbatchsForFood);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Foodmaterial> foodmaterialsForFood = new HashSet<>();
		for (Foodmaterial foodmaterial_Food : food.getFoodmaterialsForFood()) {
			foodmaterialsForFood.add(foodmaterialService.findFoodmaterialByPrimaryKey(foodmaterial_Food.getId()));
		}
		food.setFoodmaterialsForFood(foodmaterialsForFood);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Foodsaleaddress> foodsaleaddresssForFood = new HashSet<>();
		for (Foodsaleaddress foodsaleaddress_Food : food.getFoodsaleaddresssForFood()) {
			foodsaleaddresssForFood
					.add(foodsaleaddressService.findFoodsaleaddressByPrimaryKey(foodsaleaddress_Food.getId()));
		}
		food.setFoodsaleaddresssForFood(foodsaleaddresssForFood);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Picture> picturesForFood = new HashSet<>();
		for (Picture picture_Food : food.getPicturesForFood()) {
			picturesForFood.add(pictureService.findPictureByPrimaryKey(picture_Food.getId()));
		}
		food.setPicturesForFood(picturesForFood);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Video> videosForFood = new HashSet<>();
		for (Video video_Food : food.getVideosForFood()) {
			videosForFood.add(videoService.findVideoByPrimaryKey(video_Food.getId()));
		}
		food.setVideosForFood(videosForFood);
	}

	@RequestMapping(value = "/restGetFoodBrand/{foodId}/brand", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFoodBrand(@PathVariable Integer foodId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(foodDAO.findFoodByPrimaryKey(foodId).getBrand(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFoodExpire/{foodId}/expire", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFoodExpire(@PathVariable Integer foodId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(foodDAO.findFoodByPrimaryKey(foodId).getExpire(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFoodStoremethod/{foodId}/storemethod", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFoodStoremethod(@PathVariable Integer foodId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(foodDAO.findFoodByPrimaryKey(foodId).getStoremethod(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFoodProducer/{foodId}/producer", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFoodProducer(@PathVariable Integer foodId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(foodDAO.findFoodByPrimaryKey(foodId).getProducer(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFoodFoodtype/{foodId}/foodtype", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFoodFoodtype(@PathVariable Integer foodId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(foodDAO.findFoodByPrimaryKey(foodId).getFoodtype(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFoodProductcode/{foodId}/productcode", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFoodProductcode(@PathVariable Integer foodId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(foodDAO.findFoodByPrimaryKey(foodId).getProductcode(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFoodTaste/{foodId}/taste", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFoodTaste(@PathVariable Integer foodId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(foodDAO.findFoodByPrimaryKey(foodId).getTaste(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFoodDetectstandards/{foodId}/detectstandards", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFoodDetectstandards(@PathVariable Integer foodId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(foodDAO.findFoodByPrimaryKey(foodId).getDetectstandardsForFood(),
				2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFoodPackingmethods/{foodId}/packingmethods", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFoodPackingmethods(@PathVariable Integer foodId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(foodDAO.findFoodByPrimaryKey(foodId).getPackingmethodsForFood(),
				2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFoodProcessmethods/{foodId}/processmethods", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFoodProcessmethods(@PathVariable Integer foodId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(foodDAO.findFoodByPrimaryKey(foodId).getProcessmethodsForFood(),
				2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFoodFoodadditives/{foodId}/foodadditives", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFoodFoodadditives(@PathVariable Integer foodId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(foodDAO.findFoodByPrimaryKey(foodId).getFoodadditivesForFood(), 2,
				cmiPagination));
	}

	@RequestMapping(value = "/restGetFoodFoodbatchs/{foodId}/foodbatchs", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFoodFoodbatchs(@PathVariable Integer foodId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(foodDAO.findFoodByPrimaryKey(foodId).getFoodbatchsForFood(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFoodFoodmaterials/{foodId}/foodmaterials", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFoodFoodmaterials(@PathVariable Integer foodId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(foodDAO.findFoodByPrimaryKey(foodId).getFoodmaterialsForFood(), 2,
				cmiPagination));
	}

	@RequestMapping(value = "/restGetFoodFoodsaleaddresss/{foodId}/foodsaleaddresss", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFoodFoodsaleaddresss(@PathVariable Integer foodId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(foodDAO.findFoodByPrimaryKey(foodId).getFoodsaleaddresssForFood(),
				2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFoodPictures/{foodId}/pictures", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFoodPictures(@PathVariable Integer foodId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(foodDAO.findFoodByPrimaryKey(foodId).getPicturesForFood(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFoodVideos/{foodId}/videos", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFoodVideos(@PathVariable Integer foodId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(foodDAO.findFoodByPrimaryKey(foodId).getVideosForFood(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListFoods", method = RequestMethod.GET)
	@ResponseBody
	public Object restListFoods() {
		return JSONObject.parse(cmiPsonService.toJsonString(foodService.loadFoods(), 2));
	}

	@RequestMapping(value = "/restListFoodsPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListFoodsPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = foodPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Food> foods = foodDAO.findAllFoods(startResult, cmiPagination.getPaginationSize());
		String foodString = cmiPsonService.toPsonString(foods, 2, cmiPagination);

		return JSONObject.parse(foodString);
	}

	@RequestMapping("/foodSelectBox")
	@ResponseBody
	public JSONObject foodSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键
			case "Brand":
				entitySet = brandService.loadBrandsByIdSet(searchValue);
				break;
			case "Expire":
				entitySet = expireService.loadExpiresByIdSet(searchValue);
				break;
			case "Storemethod":
				entitySet = storemethodService.loadStoremethodsByIdSet(searchValue);
				break;
			case "Producer":
				entitySet = producerService.loadProducersByIdSet(searchValue);
				break;
			case "Foodtype":
				entitySet = foodtypeService.loadFoodtypesByIdSet(searchValue);
				break;
			case "Productcode":
				entitySet = productcodeService.loadProductcodesByIdSet(searchValue);
				break;
			case "Taste":
				entitySet = tasteService.loadTastesByIdSet(searchValue);
				break;

			// 被引用键
			case "Detectstandard":
				entitySet = detectstandardService.loadDetectstandardsByIdSet(searchValue);
				break;

			case "Packingmethod":
				entitySet = packingmethodService.loadPackingmethodsByIdSet(searchValue);
				break;

			case "Processmethod":
				entitySet = processmethodService.loadProcessmethodsByIdSet(searchValue);
				break;
			case "Foodadditive":
				entitySet = foodadditiveService.loadFoodadditivesByIdSet(searchValue);
				break;
			case "Foodbatch":
				entitySet = foodbatchService.loadFoodbatchsByIdSet(searchValue);
				break;
			case "Foodmaterial":
				entitySet = foodmaterialService.loadFoodmaterialsByIdSet(searchValue);
				break;
			case "Foodsaleaddress":
				entitySet = foodsaleaddressService.loadFoodsaleaddresssByIdSet(searchValue);
				break;
			case "Picture":
				entitySet = pictureService.loadPicturesByIdSet(searchValue);
				break;
			case "Video":
				entitySet = videoService.loadVideosByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键
			case "Brand":
				entitySet = brandDAO.findAllBrands((pageNumber - 1) * paginationSize, paginationSize);
				count = brandService.countBrands();
				break;
			case "Expire":
				entitySet = expireDAO.findAllExpires((pageNumber - 1) * paginationSize, paginationSize);
				count = expireService.countExpires();
				break;
			case "Storemethod":
				entitySet = storemethodDAO.findAllStoremethods((pageNumber - 1) * paginationSize, paginationSize);
				count = storemethodService.countStoremethods();
				break;
			case "Producer":
				entitySet = producerDAO.findAllProducers((pageNumber - 1) * paginationSize, paginationSize);
				count = producerService.countProducers();
				break;
			case "Foodtype":
				entitySet = foodtypeDAO.findAllFoodtypes((pageNumber - 1) * paginationSize, paginationSize);
				count = foodtypeService.countFoodtypes();
				break;
			case "Productcode":
				entitySet = productcodeDAO.findAllProductcodes((pageNumber - 1) * paginationSize, paginationSize);
				count = productcodeService.countProductcodes();
				break;
			case "Taste":
				entitySet = tasteDAO.findAllTastes((pageNumber - 1) * paginationSize, paginationSize);
				count = tasteService.countTastes();
				break;

			// 被引用键
			case "Detectstandard":
				entitySet = detectstandardDAO.findAllDetectstandards((pageNumber - 1) * paginationSize, paginationSize);
				count = detectstandardService.countDetectstandards();
				break;

			case "Packingmethod":
				entitySet = packingmethodDAO.findAllPackingmethods((pageNumber - 1) * paginationSize, paginationSize);
				count = packingmethodService.countPackingmethods();
				break;

			case "Processmethod":
				entitySet = processmethodDAO.findAllProcessmethods((pageNumber - 1) * paginationSize, paginationSize);
				count = processmethodService.countProcessmethods();
				break;
			case "Foodadditive":
				entitySet = foodadditiveDAO.findAllFoodadditives((pageNumber - 1) * paginationSize, paginationSize);
				count = foodadditiveService.countFoodadditives();
				break;
			case "Foodbatch":
				entitySet = foodbatchDAO.findAllFoodbatchs((pageNumber - 1) * paginationSize, paginationSize);
				count = foodbatchService.countFoodbatchs();
				break;
			case "Foodmaterial":
				entitySet = foodmaterialDAO.findAllFoodmaterials((pageNumber - 1) * paginationSize, paginationSize);
				count = foodmaterialService.countFoodmaterials();
				break;
			case "Foodsaleaddress":
				entitySet = foodsaleaddressDAO.findAllFoodsaleaddresss((pageNumber - 1) * paginationSize,
						paginationSize);
				count = foodsaleaddressService.countFoodsaleaddresss();
				break;
			case "Picture":
				entitySet = pictureDAO.findAllPictures((pageNumber - 1) * paginationSize, paginationSize);
				count = pictureService.countPictures();
				break;
			case "Video":
				entitySet = videoDAO.findAllVideos((pageNumber - 1) * paginationSize, paginationSize);
				count = videoService.countVideos();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键
			case "Brand":
				entitySet = brandDAO.findBrandByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = brandService.countBrandsByName(queryword);
				break;
			case "Expire":
				entitySet = expireDAO.findExpireByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = expireService.countExpiresByName(queryword);
				break;
			case "Storemethod":
				entitySet = storemethodDAO.findStoremethodByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = storemethodService.countStoremethodsByName(queryword);
				break;
			case "Producer":
				entitySet = producerDAO.findProducerByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = producerService.countProducersByName(queryword);
				break;
			case "Foodtype":
				entitySet = foodtypeDAO.findFoodtypeByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = foodtypeService.countFoodtypesByName(queryword);
				break;
			case "Productcode":
				entitySet = productcodeDAO.findProductcodeByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = productcodeService.countProductcodesByName(queryword);
				break;
			case "Taste":
				entitySet = tasteDAO.findTasteByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = tasteService.countTastesByName(queryword);
				break;

			// 被引用键
			case "Detectstandard":
				entitySet = detectstandardDAO.findDetectstandardByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = detectstandardService.countDetectstandardsByName(queryword);
				break;

			case "Packingmethod":
				entitySet = packingmethodDAO.findPackingmethodByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = packingmethodService.countPackingmethodsByName(queryword);
				break;

			case "Processmethod":
				entitySet = processmethodDAO.findProcessmethodByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = processmethodService.countProcessmethodsByName(queryword);
				break;
			case "Foodadditive":
				entitySet = foodadditiveDAO.findFoodadditiveByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = foodadditiveService.countFoodadditivesByName(queryword);
				break;
			case "Foodbatch":
				entitySet = foodbatchDAO.findFoodbatchByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = foodbatchService.countFoodbatchsByName(queryword);
				break;
			case "Foodmaterial":
				entitySet = foodmaterialDAO.findFoodmaterialByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = foodmaterialService.countFoodmaterialsByName(queryword);
				break;
			case "Foodsaleaddress":
				entitySet = foodsaleaddressDAO.findFoodsaleaddressByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = foodsaleaddressService.countFoodsaleaddresssByName(queryword);
				break;
			case "Picture":
				entitySet = pictureDAO.findPictureByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = pictureService.countPicturesByName(queryword);
				break;
			case "Video":
				entitySet = videoDAO.findVideoByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = videoService.countVideosByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
